package com.qjquestion.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.qjquestion.dto.customer.CustomerDto;
import com.qjquestion.exceptions.BusinessException;
import com.qjquestion.model.Result;
import com.qjquestion.service.CustomerService;
import com.qjquestion.service.WeiXinApiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
@Tag(name = "登录")
public class LoginController {

    @Resource
    private CustomerService customerService;
    @Resource
    private WeiXinApiService weiXinApiService;

    @GetMapping("wxAuth")
    @Operation(summary = "会员登录")
    public Result WxLogin(@RequestParam String code) {
       String OpenId = weiXinApiService.getOpenid(code);
       if(!OpenId.isBlank()){
           var entity = new CustomerDto();
           entity.setOpenId(OpenId);
           var customerVo = customerService.createCustomer(entity);
           StpUtil.login(customerVo.getId());
       }else{
           return Result.fail("登录失败");
       }
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 第3步，返回给前端
        return Result.success(tokenInfo);
    }
}
